package com.filldream.fastboot.common.okutil.stock.cf;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.filldream.fastboot.common.constant.enums.StockFstEnum;
import com.filldream.fastboot.common.constant.enums.StockMarketUtil;
import com.filldream.fastboot.common.okutil.stock.cf.kline.GetKLineSTO;
import com.filldream.fastboot.common.okutil.stock.cf.kline.KLineDTO;
import com.filldream.fastboot.common.okutil.stock.cf.kline.KLineItemDTO;
import com.filldream.fastboot.common.stockUtils.ths.ThsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CfKLineUtil {

    public static void main(String[] args) {
        GetKLineSTO sto = new GetKLineSTO();
        sto.setSearchCode("sz002456");
        List<KLineItemDTO> list = CfKLineUtil.getKLine(sto).getList();
        list.stream().forEach(System.out::println);
    }

    /**
     * 获取K线图数据
     *  1、分时 2、五日 3、日K 4、周K 5、月K 6、1分 7、5分 8、15分 9、30分 10、60分 11、季K 12、年K 13-半年
     * @param sto
     * @return
     */
    public static KLineDTO getKLine(@RequestBody GetKLineSTO sto ){
        KLineDTO result = new KLineDTO();
        //处理K线类型
        String cfKLineType = StockFstEnum.getByType(sto.getType()).getCfKType();
        String codePrefix = sto.getSearchCode().substring(0,2);
        String cfCode = StockMarketUtil.getCfImgIdBySearchCode(sto.getSearchCode());
        String url;
        Boolean isShowFst = sto.getType().equals(1) || sto.getType().equals(2);
        if( isShowFst ){
            url = "https://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f17&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ut=fa5fd1943c7b386f172d6893dbfba10b&secid="+cfCode+"&ndays="+cfKLineType+"&iscr=0&iscca=0&cb=jsonp1749102318805";
        }else{
            url = "https://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&ut=fa5fd1943c7b386f172d6893dbfba10b&rtntype=6&secid="+cfCode+"&klt="+cfKLineType+"&fqt=1&cb=jsonp1749091769567";
        }
        result.setCfKLineType( cfKLineType );
        result.setCodePrefix( codePrefix );
        List<KLineItemDTO> resultList = new ArrayList<>();
        try{
            String urlResult =  HttpUtil.get( url );
            urlResult = urlResult.substring( urlResult.indexOf("{"), urlResult.length()-2);
            JSONObject jsonObject = JSONObject.parseObject(urlResult);
            JSONArray klinesArr = jsonObject.getJSONObject("data").getJSONArray(isShowFst ? "trends" : "klines");
            result.setPriceDecimal( jsonObject.getJSONObject("data").getInteger("decimal") );
            JSONArray hisPrePrices = null;
            if( isShowFst && jsonObject.getJSONObject("data").containsKey("hisPrePrices")){
                hisPrePrices = jsonObject.getJSONObject("data").getJSONArray("hisPrePrices");
            }
            for (int i = 0; i < klinesArr.size(); i++) {
                String itemStr = klinesArr.get(i).toString();
                KLineItemDTO item = init(itemStr, isShowFst, sto.getType());
                //分时图的需要手动计算涨跌幅
                if( isShowFst && hisPrePrices!= null ){
                    String itemDayStr = DateUtil.parse(item.getOriginalDate()).toString("yyyyMMdd");
                    for (int j = 0; j < hisPrePrices.size(); j++) {
                        String preDateStr = hisPrePrices.getJSONObject(j).getString("date");
                        String prePriceStr = hisPrePrices.getJSONObject(j).getString("prePrice");
                        if( preDateStr.equals(itemDayStr) ){
                            result.setPreClosePrice( result.getPreClosePrice() == null ? new BigDecimal(prePriceStr).setScale(result.getPriceDecimal(), RoundingMode.HALF_UP) : result.getPreClosePrice() );
                            item.setZdf(  (( item.getPrice().subtract(result.getPreClosePrice()) ).divide( result.getPreClosePrice(),4,RoundingMode.HALF_UP )).multiply(  new BigDecimal("100"))   );
                            result.initPriceAndAvgPriceZdf(item.getZdf());
                            if( item.getAvgPrice() != null && item.getAvgPrice().compareTo(BigDecimal.ZERO) > 0 ){
                                result.initPriceAndAvgPriceZdf(  (( item.getAvgPrice().subtract(result.getPreClosePrice()) ).divide( result.getPreClosePrice(),4,RoundingMode.HALF_UP )).multiply(  new BigDecimal("100"))   );
                            }
                        }
                    }
                }
                item.setOriginalDate(null);
                resultList.add( item );
            }
        }catch (Exception e){
            log.error("获取股票K线图异常",e);
        }
        result.setList( resultList );
        result.initHumanVolume();
        return result;
    }

    /**
     * 初始化数据
     * @param item
     * @param isFst 是否渲染分时图样式 true-是 false-否
     * @return
     */
    public static KLineItemDTO init(String item, Boolean isFst, Integer type){
        String[] dataArr = item.split(",");
        KLineItemDTO result = new KLineItemDTO();
        result.setOriginalDate(dataArr[0]);
        if( isFst ){
            result.setDate(  dataArr[0].substring( type.equals(1) ? 11 : 5 ) );
            result.setPrice(new BigDecimal(dataArr[2]));
            result.setAvgPrice(new BigDecimal(dataArr[7]).setScale(3, RoundingMode.HALF_UP));
            result.setVolume(new BigDecimal(dataArr[6]));
        }else {
            result.setDate( dataArr[0].substring( 2 ) );
            result.setOpen(new BigDecimal(dataArr[1]));
            result.setClose(new BigDecimal(dataArr[2]));
            result.setHigh(new BigDecimal(dataArr[3]));
            result.setLow(new BigDecimal(dataArr[4]));
            result.setVolume(new BigDecimal(dataArr[6]));
            result.setZf(new BigDecimal(dataArr[7]));
            result.setZdf(new BigDecimal(dataArr[8]));
            result.setZde(new BigDecimal(dataArr[9]));
            result.setHsl(new BigDecimal(dataArr[10]));
        }
        return result;
    }



}
